const User = require('../models/User');
const logger = require('../utils/logger');
const {
  successResponse,
  errorResponse,
  notFoundResponse,
  conflictResponse,
  paginatedResponse,
  internalErrorResponse
} = require('../utils/response');

/**
 * 获取用户列表（管理员）
 */
const getUserList = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      role,
      status,
      keyword,
      startDate,
      endDate
    } = req.query;

    // 构建查询条件
    const query = {};

    if (role) {
      query.role = role;
    }

    if (status) {
      query.status = status;
    }

    if (keyword) {
      query.$or = [
        { username: { $regex: keyword, $options: 'i' } },
        { email: { $regex: keyword, $options: 'i' } },
        { 'profile.name': { $regex: keyword, $options: 'i' } }
      ];
    }

    if (startDate && endDate) {
      query.createdAt = {
        $gte: new Date(startDate),
        $lte: new Date(endDate)
      };
    }

    // 计算分页
    const skip = (parseInt(page) - 1) * parseInt(limit);

    // 查询用户
    const [users, total] = await Promise.all([
      User.find(query)
        .select('-password -refreshTokens -passwordResetToken')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(parseInt(limit)),
      User.countDocuments(query)
    ]);

    return paginatedResponse(res, users, {
      page: parseInt(page),
      limit: parseInt(limit),
      total
    }, '获取用户列表成功');

  } catch (error) {
    logger.error('获取用户列表失败:', {
      error: error.message,
      stack: error.stack,
      query: req.query
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 获取用户详情
 */
const getUserById = async (req, res) => {
  try {
    const { userId } = req.params;

    const user = await User.findById(userId)
      .select('-password -refreshTokens -passwordResetToken');

    if (!user) {
      return notFoundResponse(res, '用户');
    }

    return successResponse(res, { user }, '获取用户信息成功');

  } catch (error) {
    logger.error('获取用户详情失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 更新用户信息
 */
const updateUser = async (req, res) => {
  try {
    const { userId } = req.params;
    const updates = req.body;

    // 不允许直接更新的字段
    const restrictedFields = [
      'password', 'email', 'refreshTokens', 'passwordResetToken',
      'loginAttempts', 'accountLockedUntil', 'lastFailedLogin'
    ];

    restrictedFields.forEach(field => {
      delete updates[field];
    });

    // 查找并更新用户
    const user = await User.findById(userId);
    if (!user) {
      return notFoundResponse(res, '用户');
    }

    // 检查用户名是否已被其他用户使用
    if (updates.username && updates.username !== user.username) {
      const existingUser = await User.findOne({ username: updates.username });
      if (existingUser && existingUser._id.toString() !== userId) {
        return conflictResponse(res, '用户名已被使用');
      }
    }

    // 更新用户信息
    Object.assign(user, updates);
    user.updatedAt = new Date();
    await user.save();

    logger.info('用户信息更新成功:', {
      userId: user._id,
      updatedFields: Object.keys(updates),
      updatedBy: req.user._id
    });

    // 返回更新后的用户信息
    const userResponse = user.toJSON();
    delete userResponse.password;
    delete userResponse.refreshTokens;

    return successResponse(res, { user: userResponse }, '用户信息更新成功');

  } catch (error) {
    logger.error('更新用户信息失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId,
      updates: req.body
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 更新用户状态（激活/禁用）
 */
const updateUserStatus = async (req, res) => {
  try {
    const { userId } = req.params;
    const { status } = req.body;

    const user = await User.findById(userId);
    if (!user) {
      return notFoundResponse(res, '用户');
    }

    // 不能禁用管理员账户
    if (user.role === 'admin' && status === 'inactive') {
      return errorResponse(res, '不能禁用管理员账户', 400);
    }

    user.status = status;
    user.updatedAt = new Date();
    await user.save();

    logger.info('用户状态更新成功:', {
      userId: user._id,
      newStatus: status,
      updatedBy: req.user._id
    });

    return successResponse(res, {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        status: user.status
      }
    }, `用户已${status === 'active' ? '激活' : '禁用'}`);

  } catch (error) {
    logger.error('更新用户状态失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 更新用户角色（管理员）
 */
const updateUserRole = async (req, res) => {
  try {
    const { userId } = req.params;
    const { role } = req.body;

    const user = await User.findById(userId);
    if (!user) {
      return notFoundResponse(res, '用户');
    }

    // 检查是否尝试修改最后一个管理员的角色
    if (user.role === 'admin' && role !== 'admin') {
      const adminCount = await User.countDocuments({ role: 'admin' });
      if (adminCount <= 1) {
        return errorResponse(res, '至少需要保留一个管理员账户', 400);
      }
    }

    const oldRole = user.role;
    user.role = role;
    user.updatedAt = new Date();
    await user.save();

    logger.info('用户角色更新成功:', {
      userId: user._id,
      oldRole,
      newRole: role,
      updatedBy: req.user._id
    });

    return successResponse(res, {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    }, '用户角色更新成功');

  } catch (error) {
    logger.error('更新用户角色失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 删除用户（软删除）
 */
const deleteUser = async (req, res) => {
  try {
    const { userId } = req.params;

    const user = await User.findById(userId);
    if (!user) {
      return notFoundResponse(res, '用户');
    }

    // 不能删除管理员账户
    if (user.role === 'admin') {
      return errorResponse(res, '不能删除管理员账户', 400);
    }

    // 软删除：设置状态为deleted
    user.status = 'deleted';
    user.deletedAt = new Date();
    user.updatedAt = new Date();
    await user.save();

    logger.info('用户删除成功:', {
      userId: user._id,
      deletedBy: req.user._id
    });

    return successResponse(res, null, '用户删除成功');

  } catch (error) {
    logger.error('删除用户失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 获取用户统计信息
 */
const getUserStats = async (req, res) => {
  try {
    const [
      totalUsers,
      activeUsers,
      inactiveUsers,
      roleStats,
      recentUsers
    ] = await Promise.all([
      User.countDocuments({ status: { $ne: 'deleted' } }),
      User.countDocuments({ status: 'active' }),
      User.countDocuments({ status: 'inactive' }),
      User.aggregate([
        { $match: { status: { $ne: 'deleted' } } },
        { $group: { _id: '$role', count: { $sum: 1 } } },
        { $sort: { count: -1 } }
      ]),
      User.find({ status: { $ne: 'deleted' } })
        .select('username email role createdAt')
        .sort({ createdAt: -1 })
        .limit(5)
    ]);

    const stats = {
      total: totalUsers,
      active: activeUsers,
      inactive: inactiveUsers,
      byRole: roleStats.reduce((acc, item) => {
        acc[item._id] = item.count;
        return acc;
      }, {}),
      recent: recentUsers
    };

    return successResponse(res, { stats }, '获取用户统计成功');

  } catch (error) {
    logger.error('获取用户统计失败:', {
      error: error.message,
      stack: error.stack
    });

    return internalErrorResponse(res, error);
  }
};

/**
 * 重置用户密码（管理员）
 */
const resetUserPassword = async (req, res) => {
  try {
    const { userId } = req.params;
    const { newPassword } = req.body;

    const user = await User.findById(userId);
    if (!user) {
      return notFoundResponse(res, '用户');
    }

    // 更新密码
    user.password = newPassword;
    
    // 清除所有刷新令牌（强制重新登录）
    user.refreshTokens = [];
    
    // 重置登录失败记录
    user.loginAttempts = 0;
    user.accountLockedUntil = undefined;
    user.lastFailedLogin = undefined;
    
    user.updatedAt = new Date();
    await user.save();

    logger.info('管理员重置用户密码成功:', {
      userId: user._id,
      adminId: req.user._id
    });

    return successResponse(res, null, '密码重置成功');

  } catch (error) {
    logger.error('重置用户密码失败:', {
      error: error.message,
      stack: error.stack,
      userId: req.params.userId
    });

    return internalErrorResponse(res, error);
  }
};

module.exports = {
  getUserList,
  getUserById,
  updateUser,
  updateUserStatus,
  updateUserRole,
  deleteUser,
  getUserStats,
  resetUserPassword
};